package iot.ht.controller.htlogin;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import iot.core.annotation.Auth;
import iot.core.annotation.Log;
import iot.core.data.TreeViewNode;
import iot.core.data.mapper.HTRoleMenuMapper;
import iot.core.enums.AuthType;
import iot.core.exception.MyException;
import iot.core.manager.auth.AuthManager;
import iot.core.manager.auth.HTDeptBaseDto;
import iot.core.manager.auth.LoginDto;
import iot.core.manager.auth.LoginUserPwdDto;
import iot.core.springboot.MyThreadLocal;
import iot.ht.controller.htuser.data.HTUserDetailQto;
import iot.ht.controller.htuser.data.HTUserDto;
import iot.ht.controller.htuser.service.IHTUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/htlogin")
@Tag(name = "登录", description = "登录及获取个人信息")

public class HTLoginController {
    @Autowired
    IHTUserService ihtUserService;
    @Autowired
    HTRoleMenuMapper htRoleMenuMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    HttpServletRequest req;
    @Autowired
    HttpServletResponse res;
    @Autowired
    Environment environment;
    @Auth(authType = AuthType.None)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @GetMapping("/captcha")
    @Operation(summary = "验证码", description = "")
    public  void   captcha(@RequestParam String id) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 10);
        // 将验证码放到session中以供前端获取展示
        String code = lineCaptcha.getCode();//真实验证码
        redisTemplate.opsForValue().set("captcha:"+id,code);
        lineCaptcha.write(res.getOutputStream());
        res.setContentType("image/png");
    }


    @Auth(authType = AuthType.None)
    @Log(logNeed = false,logTemplete ="",logPin = false,logPout = false)
    @PostMapping("/login")
    @Operation(summary = "登录", description = "")
    public  String login(@RequestBody LoginDto mm){
        var debug=environment.getProperty("debug");
        if(!"true".equals(debug)){
            if(!StringUtils.hasText(mm.getYZM_Id())){
                throw  new MyException("验证码错误");
            }
            var yzm=redisTemplate.opsForValue().get("captcha:"+mm.getYZM_Id());
            if(yzm==null){
                throw  new MyException("验证码错误");
            }
            yzm=yzm.toLowerCase();
            if(!mm.getYZM().toLowerCase().equals(yzm)){
                throw  new MyException("验证码错误");
            }

        }

        return AuthManager.getInstance().login(mm);
    }

    @Auth(authType = AuthType.None)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @PostMapping("/getdept")
    @Operation(summary = "获取用户机构", description = "")
    public  List<HTDeptBaseDto>  getDept(@RequestBody LoginDto mm ){
        var m2=new LoginUserPwdDto();
        m2.setEName(mm.getEName());
        m2.setPWD(mm.getPWD());
        return AuthManager.getInstance().loginCheck(m2);
    }



    @Auth(authType = AuthType.Login)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @PostMapping("/getuserinfo")
    @Operation(summary = "获取个人信息", description = "")
    public HTUserDto getUserInfo(  ){
        var su= MyThreadLocal.get().getSu();
        var qm=new HTUserDetailQto();
        qm.setId(su.getCrt_UId() );
        qm.setHTDept_Id(su.getHTDept_Id() );
        var m= ihtUserService.Detail(qm);

        return m;
    }

    @Auth(authType = AuthType.Login)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @PostMapping("/getmenu")
    @Operation(summary = "获取个人菜单", description = "")
    public List<TreeViewNode>  getMenu(  ){
        var su= MyThreadLocal.get().getSu();
        var rid=su.getHTRoles().stream().map(a->a.getId()).collect(Collectors.toList());
        var lHTMenu_Ids=htRoleMenuMapper.getRolesMenuIds(rid);
        var l=AuthManager.getInstance().getMenuByHTPlatIdAsync(su.getHTPlat_Id() );
        DealMenu(null,l, lHTMenu_Ids);
        return l;
    }
    void DealMenu(TreeViewNode tnp,List<TreeViewNode> ltn,List<Long> lid)
    {
        var l = tnp==null?ltn:tnp.getChildren();
        for(var i=l.size()-1;i>=0;i--)
        {
            var tvn = l.get(i) ;
            if (lid.contains(tvn.getId()))
            {
                DealMenu(tvn,ltn, lid);
            }
            else
            {
                l.remove(tvn);
            }
        }

    }
}
